/**
 * Axios 客户端配置
 *
 * @author Claude
 */

import axios, {type AxiosInstance} from 'axios'
import {API_BASE_PATH} from '@/constants/api'

/**
 * 创建axios实例的公共配置
 */
const createApiClient = (): AxiosInstance => {
    return axios.create({
        baseURL: API_BASE_PATH,
        timeout: 10000,
        headers: {
            'Content-Type': 'application/json;charset=utf-8'
        },
        // 确保请求和响应使用正确的字符编码
        transformRequest: [(data, headers) => {
            // 确保请求头包含字符编码信息
            if (headers && typeof headers.setContentType === 'function') {
                headers.setContentType('application/json;charset=utf-8')
            }
            return JSON.stringify(data)
        }],
        transformResponse: [(data) => {
            // 确保响应数据正确解析
            if (typeof data === 'string') {
                try {
                    return JSON.parse(data)
                } catch {
                    return data
                }
            }
            return data
        }]
    })
}

// 创建需要认证的axios实例
export const apiClient: AxiosInstance = createApiClient()

// 创建不需要认证的axios实例
export const publicClient: AxiosInstance = createApiClient()